/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package beans;

import com.icesoft.faces.component.ext.RowSelectorEvent;
import com.icesoft.faces.component.selectinputtext.SelectInputText;
import core.School;
import db.JDBC.JdbcDaoFactory;
import db.JDBC.core.SchoolJdbcDAOCore;
import db.core.interfaces.SchoolDAOCore;
import db.interfaces.SchoolDAO;
import db.xml.SchoolXMLDAO;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.event.ActionEvent;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;

/**
 *
 * @author Anton
 */
public class SimpleSchoolListBean extends AutoCompleteBean {

    @PostConstruct
    public void init() {
        initDbColumns();
        ascending = true;
        oldSearchString = searchString = "";
        oldSortColumnName = sortColumnName = idColumnName;
        search(null);
    }
    List<SimpleSchoolBean> schoolList;
    private SimpleSchoolBean selectedSchool;
    private SimpleSchoolBean addSchool; // used for storing shop to be added
    private int selectedRow;
    private boolean editMode;
    private boolean addMode;
    private String oldSearchString;
    /*
     *  Sortable data tables
     */
    private final static String idColumnName = "id #";
    private final static String nameColumnName = "School Name";
    private final static String descriptionColumnName = "description";
    private final static String weblinkColumnName = "weblink";
    private final static String xmlsourceColumnName = "XML source link";
    private final static String statusColumnName = "latest status";
    private final static String dbIdColumnName = "id";
    private final static String dbNameColumnName = "name";
    private final static String dbDescriptionColumnName = "description";
    private final static String dbWeblinkColumnName = "weblink";
    private final static String dbXmlsourceColumnName = "xmlsource";
    private HashMap<String, String> lookupDbColumnName;
    boolean ascending;
    boolean oldAscending;
    private String sortColumnName;
    private String oldSortColumnName;

    private void initDbColumns() {
        lookupDbColumnName = new HashMap<String, String>();
        lookupDbColumnName.put(idColumnName, dbIdColumnName);
        lookupDbColumnName.put(nameColumnName, dbNameColumnName);
        lookupDbColumnName.put(descriptionColumnName, dbDescriptionColumnName);
        lookupDbColumnName.put(weblinkColumnName, dbWeblinkColumnName);
        lookupDbColumnName.put(xmlsourceColumnName, dbXmlsourceColumnName);
    }

    public String getIdColumnName() {
        return idColumnName;
    }

    public String getNameColumnName() {
        return nameColumnName;
    }

    public String getDescriptionColumnName() {
        return descriptionColumnName;
    }

    public String getWeblinkColumnName() {
        return weblinkColumnName;
    }

    public String getXmlsourceColumnName() {
        return xmlsourceColumnName;
    }

    public String getStatusColumnName() {
        return statusColumnName;
    }

    public void setSortColumnName(String name) {
        this.oldSortColumnName = this.sortColumnName;
        this.sortColumnName = name;
    }

    public String getSortColumnName() {
        return sortColumnName;
    }

    public void setAscending(boolean ascending) {
        oldAscending = this.ascending;
        this.ascending = ascending;
    }

    public boolean getAscending() {
        return ascending;
    }

    public List<SimpleSchoolBean> getSchoolList() {
        if (oldAscending != ascending || !sortColumnName.equals(oldSortColumnName)) {
            search(null);
        }
        return schoolList;
    }

    public void setSchoolList(List<SimpleSchoolBean> schoolList) {
        this.schoolList = schoolList;
    }

    /*
     * Selection and editing
     *
     */
    public void setSelected(RowSelectorEvent ev) {
        this.selectedRow = ev.getRow();
        this.selectedSchool = new SimpleSchoolBean(
                schoolList.get(ev.getRow()));
    }

    public SimpleSchoolBean getSelected() {
        return selectedSchool;
    }

    public SimpleSchoolBean getAddSchool() {
        return addSchool;
    }

    public void setAddSjop(SimpleSchoolBean addSchool) {
        this.addSchool = addSchool;
    }

    public boolean getEditMode() {
        return editMode;
    }

    public void setEditMode(boolean editMode) {

        this.editMode = editMode;
    }

    public void enableEditMode(ActionEvent e) {
        if (selectedSchool != null) {
            editMode = true;
        }
    }

    public void disableEditMode(ActionEvent e) {
        editMode = false;
    }

    public boolean getAddMode() {
        return addMode;
    }

    public void setAddMode(boolean addMode) {

        this.addMode = addMode;
    }

    public void enableAddMode(ActionEvent e) {
        addSchool = new SimpleSchoolBean(new School());
        addMode = true;

    }

    public void disableAddMode(ActionEvent e) {
        addMode = false;
    }

    public void updateSchool(ActionEvent e) {
        
        SchoolXMLDAO xmlDAO = new SchoolXMLDAO();
        String XMLSource = selectedSchool.getXmlSource();
        long schoolId = selectedSchool.getId();        
        School newSchool = xmlDAO.getSchoolByURL(XMLSource);        
        
        if(newSchool == null)
        {
            newSchool = new School();
        }
        else
            schoolList.get(selectedRow).setStatusByInt(2);
        newSchool.setXMLSource(XMLSource);
        newSchool.setId(schoolId);

        SchoolJdbcDAOCore.getInstance().updateSchool(newSchool);
        schoolList.get(selectedRow).setSchool(newSchool);
        editMode = false;

    }

    public void addSchool(ActionEvent e) {
        SchoolXMLDAO xmlDAO = new SchoolXMLDAO();
        String XMLSource = addSchool.getXmlSource();
        School newSchool = xmlDAO.getSchoolByURL(XMLSource);
        if(newSchool == null)
        {
            newSchool = new School();
        }

        newSchool.setXMLSource(XMLSource);
        SchoolJdbcDAOCore.getInstance().addSchool(newSchool);
        search(null);
        addMode = false;
    }

    public void deleteSchool(ActionEvent e) {

        SchoolJdbcDAOCore.getInstance().deleteSchool(selectedSchool.getSchool());
        schoolList.remove(selectedRow);
        editMode = false;

    }


    /*
     * Search
     *
     *
     */
    public void search(ActionEvent e) {
        SchoolDAO sDao = JdbcDaoFactory.getInstance().getSchoolJdbcDAO();
        if (sDao == null) {
            return;
        }

        if (lookupDbColumnName.get(sortColumnName) == null) {
            return;
        }


        List<SimpleSchoolBean> newSchoolList;

        newSchoolList = new ArrayList<SimpleSchoolBean>();

        // new search! Should recieve actionEvent
        if (e != null) {
            oldSearchString = searchString;
        }

        Collection<School> schools = sDao.searchForSchoolsByParameters(oldSearchString,
                lookupDbColumnName.get(sortColumnName), ascending);
        if (schools != null) {
            for (School school : schools) {
                newSchoolList.add(new SimpleSchoolBean(school));
            }
        }


        this.schoolList = newSchoolList;
        oldAscending = ascending;
        oldSortColumnName = sortColumnName;

    }

    public void showAll(ActionEvent e) {
        this.oldSearchString = "";
        search(null);
    }

    public void updateSchools(ActionEvent e)
    {
        SchoolXMLDAO dao = new SchoolXMLDAO();
        SchoolJdbcDAOCore dbDao = SchoolJdbcDAOCore.getInstance();
        for(SimpleSchoolBean schoolBean: schoolList)
        {
            String XMLSource = schoolBean.getXmlSource();
            long schoolId = schoolBean.getId();
            long startTime = System.currentTimeMillis();
            School school = dao.getSchoolByURL(XMLSource);
            long stopTime = System.currentTimeMillis();
            System.out.println("Hämta via XML, time was " + (stopTime - startTime) + " miliseconds.");

            if(school == null)
                schoolBean.setStatusByInt(1); //failed update, do nothing to database!
            else
            {
                schoolBean.setSchool(school);
                schoolBean.setXmlSource(XMLSource);
                schoolBean.setId(schoolId);
                startTime = System.currentTimeMillis();
                dbDao.updateSchool(school);
                stopTime = System.currentTimeMillis();
                System.out.println("Uppdatera i db, time was " + (stopTime - startTime) + " miliseconds.");
                schoolBean.setStatusByInt(2);
            }

        }


    }

    public void selectInputValueChanged(ValueChangeEvent event) {
        if (event.getComponent() instanceof SelectInputText) {
            SelectInputText autoComplete = (SelectInputText) event.getComponent();
            String newWord = (String) event.getNewValue();
            matchPossibilities = generateMatches(newWord, 10);

            if (autoComplete.getSelectedItem() != null) {
                searchString = (String) autoComplete.getSelectedItem().getValue();
            }
        }
    }

    public List<SelectItem> generateMatches(String searchWord, int maxMatches) {
        ArrayList<String> matchList = new ArrayList();
        List<SelectItem> returnCollection = new ArrayList<SelectItem>();

        if ((searchWord == null) || (searchWord.trim().length() == 0)) {
            return returnCollection;
        }

        SchoolDAOCore schoolDAO = SchoolJdbcDAOCore.getInstance();

        for (String s : schoolDAO.searchForStringSchools(searchWord, maxMatches)) {
            matchList.add(s);
        }
        Collections.sort(matchList);

        if (matchList.size() < maxMatches) {
            maxMatches = matchList.size();
        }

        for (String s : matchList.subList(0, maxMatches)) {
            returnCollection.add(new SelectItem(s));
        }
        return returnCollection;
    }
}

